package com.action.gulimall.ware.service.impl;

import com.action.common.constant.MqConstant;
import com.action.common.constant.OrderConstant;
import com.action.common.constant.WareConstant;
import com.action.common.to.SkuStockTo;
import com.action.common.to.mq.OrderTo;
import com.action.common.to.mq.StockDetailTo;
import com.action.common.to.mq.StockLockedTo;
import com.action.common.utils.R;
import com.action.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.action.gulimall.ware.entity.WareOrderTaskEntity;
import com.action.gulimall.ware.fegin.ProductFeignService;
import com.action.gulimall.ware.fegin.OrderFeignService;
import com.action.gulimall.ware.service.WareOrderTaskDetailService;
import com.action.gulimall.ware.service.WareOrderTaskService;
import com.action.gulimall.ware.vo.OrderItemVo;
import com.action.gulimall.ware.vo.SkuHasStockVo;
import com.action.gulimall.ware.vo.WareSkuLockVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.action.common.utils.PageUtils;
import com.action.common.utils.Query;

import com.action.gulimall.ware.dao.WareSkuDao;
import com.action.gulimall.ware.entity.WareSkuEntity;
import com.action.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    OrderFeignService orderFeignService;
    @Autowired
    WareSkuDao wareSkuDao;
    @Autowired
    WareOrderTaskService wareOrderTaskService;
    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId) && !"0".equalsIgnoreCase(skuId)) {
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId) && !"0".equalsIgnoreCase(wareId)) {
            queryWrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {

        //1、判读如果没有这个库存记录新增
        List<WareSkuEntity> wareSkuEntities = this.list(
                new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));

        if (wareSkuEntities == null || wareSkuEntities.size() == 0) {
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败整个事务无需回滚
            //1、自己catch异常
            try{
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");
                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
                log.error("远程获取skuId="+skuId+"名称出现异常",e);
            }
            //添加库存信息
            this.save(wareSkuEntity);
        } else {
            //修改库存信息
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }
    }

    @Override
    public List<SkuStockTo> skusHasStocks(List<Long> skuIds){
        List<SkuStockTo> skuStockTos = skuIds.stream().map(skuId -> {
            SkuStockTo skuStockTo = new SkuStockTo();
            Long stock = baseMapper.skuIdStock(skuId);
            if(stock==null){
                skuStockTo.setHasStock(Boolean.FALSE);
            }else{
                skuStockTo.setHasStock(Boolean.TRUE);
            }
            return skuStockTo;
        }).collect(Collectors.toList());
        return skuStockTos;
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> skuHasStockVos = skuIds.stream().map(item -> {
            Long count = this.baseMapper.getSkuStock(item);
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(item);
            skuHasStockVo.setHasStock(count == null?Boolean.FALSE:count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return skuHasStockVos;
    }

    //@Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo lockVo) {
        Boolean[] lockSuccess ={true};
        /**
         * 保存库存工作单详情信息
         * 追溯
         */
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(lockVo.getOrderSn());
        wareOrderTaskEntity.setCreateTime(new Date());
        wareOrderTaskService.save(wareOrderTaskEntity);
        Map<Long, OrderItemVo> skuCountMap = lockVo.getLocks().stream().collect(Collectors.toMap(OrderItemVo::getSkuId, orderItemVo->orderItemVo));
        List<WareSkuEntity> wareSkuEntities = this.list(new QueryWrapper<WareSkuEntity>().in("sku_id", skuCountMap.keySet()));
        Map<Long, WareSkuEntity> wareSkuEntityMap = wareSkuEntities.stream().filter(wareSkuEntity -> {
            OrderItemVo orderItemVo = skuCountMap.get(wareSkuEntity.getSkuId());
            if(wareSkuEntity.getStock()-wareSkuEntity.getStockLocked()>=orderItemVo.getCount()){
                return Boolean.TRUE;
            }else{
                return Boolean.FALSE;
            }
        }).collect(Collectors.toMap(WareSkuEntity::getSkuId, wareSkuEntity -> wareSkuEntity));

        skuCountMap.forEach((skuId,orderItemVo)->{
            WareSkuEntity wareSkuEntity = wareSkuEntityMap.get(skuId);
            if(wareSkuEntity!=null){
                //进行锁定操作
                Long updatedNum = wareSkuDao.lockSkuStock(skuId,wareSkuEntity.getWareId(),orderItemVo.getCount());
                if(updatedNum==1){
                    //进行数据加载
                    WareOrderTaskDetailEntity taskDetailEntity = WareOrderTaskDetailEntity.builder()
                            .skuId(skuId)
                            .skuName(orderItemVo.getTitle())
                            .skuNum(orderItemVo.getCount())
                            .taskId(wareOrderTaskEntity.getId())
                            .wareId(wareSkuEntity.getWareId())
                            .lockStatus(1)
                            .build();
                    wareOrderTaskDetailService.save(taskDetailEntity);

                    //TODO 告诉MQ库存锁定成功
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(wareOrderTaskEntity.getId());
                    StockDetailTo detailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity,detailTo);
                    lockedTo.setDetailTo(detailTo);
                    rabbitTemplate.convertAndSend(MqConstant.ORDER_EXCHANGE_NAME,
                            MqConstant.ORDER_STOCK_LOCK_ROUTINGKEY,
                            lockedTo,new CorrelationData(lockVo.getOrderSn()));
                    if(lockVo.getOrderSn().length()>10){
                        int a= Long.valueOf(UUID.randomUUID().toString()).intValue();
                        log.error(a+"");
                    }
                }else{
                    lockSuccess[0]=false;
                }
            }else{
                lockSuccess[0]=false;
            }
        });
        return lockSuccess[0];
    }

    @Transactional
    //进行库存解锁
    @Override
    public void unLockStock(StockLockedTo stockLockedTo) throws Exception {
        //解锁
          //确定查询锁定记录是否存在
            //不存在 不需要进行解锁
            //存在 查看锁定记录状态
                //锁定记录状态为已锁定
                   //需要查看订单状态
                     //订单不存在或者状态为已取消 进行解锁操作
                     //不解锁
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = wareOrderTaskDetailService.getById(stockLockedTo.getDetailTo().getId());
        if(wareOrderTaskDetailEntity==null||wareOrderTaskDetailEntity.getLockStatus()!= WareConstant.WareOrderTaskDetailStatusEnum.LOCKED.getCode()){
            return;
        }else{
            //远程查询订单
            WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getById(stockLockedTo.getId());
            R r = orderFeignService.getOrderEntityByOrderSn(wareOrderTaskEntity.getOrderSn());
            OrderTo orderVo = r.getData(new TypeReference<OrderTo>(){}).get();
            if(r.getCode()==0){
                if(orderVo!=null&&orderVo.getStatus()==OrderConstant.OrderStatusEnum.CANCLED.getCode()){
                    releaseLockedStock(wareOrderTaskDetailEntity);
                }
            }else{
                throw new Exception("远程查询订单出现异常:"+ JSON.toJSONString(r));
            }
            //判断订单是否处于未支付或者取消状态
        }
    }
    /**
     * 防止订单服务卡顿，导致订单状态消息一直改不了，库存优先到期，查订单状态新建，什么都不处理
     * 导致卡顿的订单，永远都不能解锁库存
     * @param orderTo
     */
    @Transactional
    @Override
    public void unLockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新的库存解锁状态，防止重复解锁库存
        WareOrderTaskEntity orderTaskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);

        //按照工作单的id找到所有 没有解锁的库存，进行解锁
        Long id = orderTaskEntity.getId();
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id).eq("lock_status", 1));

        for (WareOrderTaskDetailEntity taskDetailEntity : list) {
            releaseLockedStock(taskDetailEntity);
        }
    }

    @Transactional
    public void releaseLockedStock(WareOrderTaskDetailEntity wareOrderTaskDetailEntity){
            //更新库存锁定详细工单状态
            wareOrderTaskDetailEntity.setLockStatus(WareConstant.WareOrderTaskDetailStatusEnum.RELEASE.getCode());
            wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
            //解锁锁定库存
            wareSkuDao.releaseLockedStock(wareOrderTaskDetailEntity.getSkuId(),
                    wareOrderTaskDetailEntity.getWareId(),
                    wareOrderTaskDetailEntity.getSkuNum());
    }
}